//
//  QDetailsOrderVC.m
//  QoilPublic
//
//  Created by 杨凯 on 16/7/7.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QDetailsOrderVC.h"
#import "QDetailsOrderCell.h"
#import "QPayMoneyVC.h"
#import "QPerfectOrderInforMationVC.h"
#import "QJudgeVC.h"
#import "QJudgeDetailsVC.h"
#import "QConfirmOrderInforMationVC.h"
#import "QDetailNoteOrderCell.h"
#import "QSmallTicketVC.h"
#import "QDetailPeopleCell.h"


#import "SheetView.h"
@interface QDetailsOrderVC ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)SheetView *sheetView;
@end

@implementation QDetailsOrderVC{

    UITableView *_tableView;
    NSArray *_titleArr;
    UIButton *_cancelBtn;//一个取消的按钮
    //UIView *_includeBtnView;
    //UIButton *_leftButton;
    //UIButton *_rightButton;
    NSArray *_textArr;
    QDetailNoteOrderCell *_noteCell;
    NSMutableArray *_evalArr;
    
}
- (id)init{
    self = [super init];
    if (self) {
        
        self.hidesBottomBarWhenPushed = YES;
        
    }
    return self;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (self.pushStyle == DetailsPushRootStyle) {
        if (self.navigationController.viewControllers.count) {
            NSMutableArray *arr = [NSMutableArray array];
            [arr addObject: self.navigationController.viewControllers.firstObject];
            [arr addObject: self.navigationController.viewControllers.lastObject];
            self.navigationController.viewControllers = arr;

        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单详情";
    
    
    //if(_detailOrderStyle == DetailsOrderfinishStyle){
        _titleArr = @[@[@"订单状态"],@[@"下单金额",@"加油单价",@"柴油标准",@"加油时间",@"加油地点",@"联系方式",@"需要发票"],@[@"备注信息"],@[@"加油金额",@"使用卡券",@"合计"],@[@"",@""],@[@"查看小票"],@[@"订单编号",@"创建时间"],@[@"星级评价",@"评价内容"]];
        
   // }else if (_detailOrderStyle == DetailsOrderdisPayStyle){
        
        //_titleArr = @[@[@"订单状态"],@[@"下单金额",@"加油单价",@"柴油标准",@"加油时间",@"加油地点",@"联系方式",@"需要发票"],@[@"备注信息"],@[@"合计"],@[@"",@""],@[@"查看小票"],@[@"订单编号",@"创建时间"]];
        
    //}else{
       // _titleArr = @[@[@"订单状态"],@[@"下单金额",@"加油单价",@"柴油标准",@"加油时间",@"加油地点",@"联系方式",@"需要发票"],@[@"备注信息"],@[@"使用卡券",@"合计"],@[@"",@""],@[@"订单编号",@"创建时间"]];
    //}
    [self createTableView];
    
    
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification:) name:kNotificationDetailPush object:nil];
    
    UIButton *navButton = [UIButton buttonWithType:UIButtonTypeCustom];
    navButton.frame = CGRectMake(0,0,55, 45);
    navButton.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    navButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [navButton setTitle:@"投诉" forState:UIControlStateNormal];
    [navButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [navButton addTarget:self action:@selector(callPhoneAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:navButton];
    self.navigationItem.rightBarButtonItem = rightItem;
    


}

- (void)setOrderId:(NSString *)orderId{
    [self requestDetailData:orderId];
}

- (void)callPhoneAction{
    
    [QViewUtility showPlayBoxView:PlayboxCallPhoneStyle myBlock:^(NSInteger index) {
        if(index == 1){
            [QViewUtility callPhone];
        }
    }];
}

- (void)notification:(NSNotification *)notification{
    NSDictionary *dic = [notification userInfo];
    CLog(@"orderId====%@",dic[@"orderId"]);
    [self requestDetailData:dic[@"orderId"]];
}

#pragma mark --- UI
- (void)createBottomBtn{
    
    _cancelBtn = [QViewUtility createButtonWithFrame:CGRectMake(0, _tableView.bottom, kScreenWidth, 50) font:17 title:@"取消订单" titleColor:[QColorUtility defaultDeepGrayColor] backgroundColor:[QColorUtility defaultBackGroundColor]];
    if (_detailOrderStyle == DetailsOrderwaitedStyle) {
        //可取消
        _cancelBtn.tag = 1;
        
        [_cancelBtn setBackgroundColor:[QColorUtility defaultBlueColor]];
        [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        
    }else if (_detailOrderStyle == DetailsOrderdisPayStyle){
        //待支付
        [_cancelBtn setBackgroundColor:[QColorUtility defaultBlueColor]];
        [_cancelBtn setTitle:@"去支付" forState:0];
        _cancelBtn.tag = 2;
        [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        
    }else if (_detailOrderStyle == DetailsOrderevaluateStyle){
        //待评价
        [_cancelBtn setBackgroundColor:[QColorUtility defaultBlueColor]];
        [_cancelBtn setTitle:@"评价" forState:0];
        _cancelBtn.tag = 3;
        [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

        
    }else if (_detailOrderStyle == DetailsOrderfinishStyle){
        //再来一单
        [_cancelBtn setTitle:@"再来一单" forState:0];
        _cancelBtn.tag = 4;
        [_cancelBtn setBackgroundColor:[QColorUtility defaultBlueColor]];
        [_cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    }
    [_cancelBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelBtn];
    
}


- (void)setDetailOrderStyle:(DetailsOrderStyle)detailOrderStyle{
    _detailOrderStyle = detailOrderStyle;
    _style = detailOrderStyle;
    [self.view addSubview:[UIView new]];
    [self createBottomBtn];
}

//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

#pragma mark --- buttonAction

- (void)buttonAction:(UIButton *)button{
    __block QDetailsOrderVC *wself = self;
    
    switch (button.tag) {
        case 1://取消订单
        {
            [QViewUtility showPlayBoxView:PlayboxcancelOrderStyle myBlock:^(NSInteger index) {
                if(index == 1){
                    [wself cancelOrderRequestData];
                }
            }];

        }
            break;
        case 2:
        {
            QPayMoneyVC * vc = [[QPayMoneyVC alloc] init];
            vc.orderId = _model.orderId;
            vc.moneyStr = _model.total;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3://评价
        {
            
            [self loadClicked];

        }
            break;
        case 4:
        {
            QPerfectOrderInforMationVC * vc = [[QPerfectOrderInforMationVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;

            
        default:
            break;
    }

}

-(void)loadClicked
{
    _sheetView = [[SheetView alloc]init];
    _sheetView.orderId = _model.orderId;
    [_sheetView showInView:[self getCurrentVC].view];
    
}


#pragma mark --- createTableView
- (void)createTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-50) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:_tableView];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QDetailsOrderCell" bundle:nil] forCellReuseIdentifier:@"QDetailsOrderCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QDetailNoteOrderCell" bundle:nil] forCellReuseIdentifier:@"QDetailNoteOrderCell"];
    
    _noteCell = [_tableView dequeueReusableCellWithIdentifier:@"QDetailNoteOrderCell"];
    
    [_tableView registerNib:[UINib nibWithNibName:@"QDetailPeopleCell" bundle:nil] forCellReuseIdentifier:@"QDetailPeopleCell"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"TableViewCell"];
    
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return _titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_titleArr[section]count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 7) {
        
        QDetailsOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailsOrderCell" forIndexPath:indexPath];
        
        cell.titleLabel.text = _titleArr[indexPath.section][indexPath.row];
        cell.indexPath = indexPath;
        cell.subTitleLabel.text = @"";
        
        if (_evalArr.count>0) {
            
            NSString *str = @"";
            
            if (indexPath.row == 0) {
                
                for (int i = 0; i<_evalArr.count-1; i++) {
                    
                    NSDictionary *tmpDic = [_evalArr objectAtIndex:i];
                    NSString *tmpStr =  [NSString stringWithFormat:@" %@:%@星 ",[tmpDic objectForKey:@"name"],[tmpDic objectForKey:@"stars"]];
                    str = [str stringByAppendingString:tmpStr];
                }
                cell.subTitleLabel.text = str;
            
            }
            if (indexPath.row == 1) {
               NSDictionary *dict =  [_evalArr lastObject];
                NSDictionary *tmpDic = [self processDictionaryIsNSNull:dict];
                if ([tmpDic.allKeys containsObject:@"content"]) {
                    cell.subTitleLabel.text = [tmpDic objectForKey:@"content"];
                    cell.subTitleLabel.textAlignment = NSTextAlignmentLeft;
                    cell.subTitleLabel.font = [UIFont systemFontOfSize:15];
                }
            }
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if(indexPath.section == 2){//备注信息
        QDetailNoteOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailNoteOrderCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if(_model){
            cell.model = _model;
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else if(indexPath.section == 4){
    
        QDetailPeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailPeopleCell" forIndexPath:indexPath];
        cell.isSend = NO;
        
        cell.indexPath = indexPath;
        if(_model){
            cell.model = _model;
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    
    }else{
        QDetailsOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDetailsOrderCell" forIndexPath:indexPath];
        
        if(_detailOrderStyle == DetailsOrderfinishStyle){
            cell.isFinish = YES;
        }else{
            cell.isFinish = NO;
        }
        
        if (_detailOrderStyle == DetailsOrderdisPayStyle) {
            cell.isPay =NO;
        }else{
            cell.isPay = YES;
        }
        
        cell.titleLabel.text = _titleArr[indexPath.section][indexPath.row];
        cell.indexPath = indexPath;
        if(_model){
            cell.model = _model;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 2){
        if(_model){
            _noteCell.model = _model;
        }
        CGFloat h = [_noteCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height+1;
            return h;
    }else{
        return 50;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if(_detailOrderStyle == DetailsOrderfinishStyle && indexPath.section == 5){
        if(_model.imgs.count > 0){
            QSmallTicketVC *vc = [[QSmallTicketVC alloc] init];
            vc.arrs = _model.imgs;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc]init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}


//判空
- (id) processDictionaryIsNSNull:(id)obj{
    const NSString *blank = @"";
    
    if ([obj isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *dt = [(NSMutableDictionary*)obj mutableCopy];
        for(NSString *key in [dt allKeys]) {
            id object = [dt objectForKey:key];
            if([object isKindOfClass:[NSNull class]]) {
                [dt setObject:blank
                       forKey:key];
            }
            else if ([object isKindOfClass:[NSString class]]){
                NSString *strobj = (NSString*)object;
                if ([strobj isEqualToString:@"<null>"]) {
                    [dt setObject:blank
                           forKey:key];
                }
            }
            else if ([object isKindOfClass:[NSArray class]]){
                NSArray *da = (NSArray*)object;
                da = [self processDictionaryIsNSNull:da];
                [dt setObject:da
                       forKey:key];
            }
            else if ([object isKindOfClass:[NSDictionary class]]){
                NSDictionary *ddc = (NSDictionary*)object;
                ddc = [self processDictionaryIsNSNull:object];
                [dt setObject:ddc forKey:key];
            }
        }
        return [dt copy];
    }
    else if ([obj isKindOfClass:[NSArray class]]){
        NSMutableArray *da = [(NSMutableArray*)obj mutableCopy];
        for (int i=0; i<[da count]; i++) {
            NSDictionary *dc = [obj objectAtIndex:i];
            dc = [self processDictionaryIsNSNull:dc];
            [da replaceObjectAtIndex:i withObject:dc];
        }
        return [da copy];
    }
    else{
        return obj;
    }
}

#pragma mark ---取消订单
- (void)cancelOrderRequestData{    
    NSString *url = [QParamService urlWithAction:@"/order/cancel"];
    NSDictionary *param = [QParamService cancelOrder:_model.orderId];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"取消成功" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
            //[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationRegisterSuccess object:nil];
            if (_pushStyle != DetailsPushRootStyle) {
                if(_cancelBlock){
                    _cancelBlock();
                }

            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:@"取消失败" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}
#pragma mark ---订单详情
- (void)requestDetailData:(NSString *)orderId{
    NSString *url = [QParamService urlWithAction:@"/order/userOrderDetail"];

    NSDictionary *param = [QParamService detailOrderid:orderId];
    [QViewUtility showMBHudToView:self.view hideBg:NO];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            _model = [QAllorderListModel objectFromDict:basModel.items];
            
            if (_detailOrderStyle == DetailsOrderfinishStyle) {
                [self requestData];
            }else if (_detailOrderStyle == DetailsOrderevaluateStyle){
                
                UIButton *button = [self.view viewWithTag:3];
                NSString *score = [self removeFloatAllZero:_model.integral];
                NSString *str = [NSString stringWithFormat:@"评价得%@积分",score];
                [button setTitle:str forState:UIControlStateNormal];
                
            }
                [_tableView reloadData];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}
//去掉小数点后面的0
-(NSString*)removeFloatAllZero:(NSString*)string
{
    NSString * testNumber = string;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    return outNumber;
}


- (void)requestCallPhoneWithOrderId{
    NSString *url = [QParamService urlWithAction:@"dialback"];
    NSDictionary *param = [QParamService callPhoneWithOrderId:_model.orderId flag:@"1"];
    [[QHttpManager sharedManager] POST:url parameterMD5:param completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"smile_image"] content:@"正在拨通中,请稍候!" btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
    
}
#pragma mark--星级文字
- (void)gainStarText{
    
    NSString *url = [QParamService urlWithAction:@"order/getEvalType"];
    NSDictionary *params = [QParamService GainStarText];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            _textArr = [basModel.items objectForKey:@"list"];

            [_tableView reloadData];
            
        }else{
            
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

- (void)requestData{
    
    NSString *url = [QParamService urlWithAction:@"selUserEvaluatetanker"];
    NSDictionary *para= [QParamService GainValuationDataWithOrderId:_model.orderId];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            NSDictionary *dic =  basModel.items;
            if ([dic.allKeys containsObject:@"evalJsonstr"]) {
                NSString *evalJsonstr = [dic objectForKey:@"evalJsonstr"];
                
                NSString *string = [evalJsonstr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
                if (string == nil) {
                    
                }
                
                NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
                NSError *err;
                _evalArr = [NSMutableArray new];
                _evalArr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers
                                                             error:&err];
                
                if (_evalArr.count>0) {
                    
                    NSString *content = [dic objectForKey:@"content"];
                    if (content != nil ||![content isEqualToString:@""]) {
                        NSDictionary *dic = @{@"content":content};
                        [_evalArr addObject:dic];
                    }
                }
                
                [_tableView reloadData];
                if(err) {
                    NSLog(@"json解析失败：%@",err);
                    
                }
            }
        }
    }];
    
}

@end
